import { useState, useRef } from "react";
import { IconSend } from "@douyinfe/semi-icons";
import { Button, Input, List } from "@douyinfe/semi-ui";

import { io, Socket } from "socket.io-client";

interface Message {
  username: String;
  message: String;
}

const Chatroom = () => {
  const [username, setUsername] = useState("xiaoming");
  const [room, setRoom] = useState("天字一号");
  const [message, setMessage] = useState("");

  const [messageList, setMessageList] = useState<Message[]>([]);
  const messageListRef = useRef(messageList);

  const [btnDisabled, setBtnDisabled] = useState(false);
  const [socket, setSocket] = useState<Socket>();

  const connect = () => {
    console.log("start connect...");
    const socket = io();
    socket.on("connect", () => {
      console.log("connected");
      socket.on("joined", (room, id) => {
        setBtnDisabled(true);
        console.log(`joined ${room}`);
      });
      socket.on("leaved", (room, id) => {});
      socket.on("message", handleMessage);

      socket.emit("join", room);

      setSocket(socket);
    });
  };

  const handleMessage = (data: Message) => {
    console.log(`received: ${data}`);
    setMessageList((list) => [...list, data]);
  };

  const sendMessage = () => {
    socket?.emit("message", room, {
      username,
      message,
    });
  };

  return (
    <div className="p-24">
      <h1>Chat room</h1>
      <div className="w-1/2 flex  justify-around" style={{ height: "60px" }}>
        <Input
          style={{ width: 200 }}
          prefix="用户名"
          showClear
          value={username}
          onChange={(value) => setUsername(value)}
          autofocus
        />
        <Input style={{ width: 200 }} prefix="房间" showClear value={room} onChange={(value) => setRoom(value)} />
        <Button disabled={btnDisabled} onClick={connect} theme={"solid"}>
          {btnDisabled ? "Connected" : "Connect"}
        </Button>
      </div>
      <div className="w-1/2">
        <List
          size="small"
          bordered
          dataSource={messageList}
          renderItem={(item) => (
            <List.Item>
              <span className="text-red-400 mr-8">{item.username}:</span> {item.message}
            </List.Item>
          )}
        />
      </div>
      <div className="w-1/2 mt-10 flex">
        <Input
          value={message}
          onChange={(value) => {
            setMessage(value);
          }}
          className="mr-4"
        />
        <Button onClick={sendMessage} theme={"solid"} icon={<IconSend />}>
          发送
        </Button>
      </div>
    </div>
  );
};

export default Chatroom;
